import 'package:flutter/material.dart';
import 'dart:async';
import '../models/exam_model.dart';
import '../models/question_model.dart';
import '../services/exam_service.dart';
import '../services/exam_state_service.dart';
import '../utils/responsive_util.dart';
import '../data/user_data.dart';
import 'result_screen.dart';
import 'dart:io';
import '../services/image_service.dart';

class ExamScreen extends StatefulWidget {
  final Exam exam;
  final ExamState? initialState; // 可选的初始状态，用于恢复考试
  final String? avatarPath; // 新增：头像路径
  
  const ExamScreen({
    super.key, 
    required this.exam, 
    this.initialState,
    this.avatarPath,
  });

  @override
  State<ExamScreen> createState() => _ExamScreenState();
}

class _ExamScreenState extends State<ExamScreen> {
  late PageController _pageController;
  int _currentIndex = 0;
  Map<String, dynamic> _answers = {}; // 存储答案，key为题目ID，value为答案
  Set<String> _markedQuestions = {}; // 存储标记的题目ID
  Timer? _timer;
  int _remainingSeconds = 0;
  bool _isSubmitting = false;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  Timer? _autoSaveTimer; // 自动保存计时器
  final ScrollController _scrollController = ScrollController();
  final Map<String, dynamic> _userAnswers = {};
  final Map<String, int> _questionIndexMap = {};
  bool _isExamSubmitted = false;
  bool _showConfirmDialog = false;
  Timer? _examTimer;
  Timer? _saveStateTimer;
  ExamResult? _examResult;
  
  // 新增：用于存储答题照片的字段
  final Map<String, List<String>> _answerImages = {};

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    
    // 如果有初始状态，恢复状态
    if (widget.initialState != null) {
      _restoreState(widget.initialState!);
    } else {
      // 创建新考试状态
      _startNewExam();
    }
    
    // 设置自动保存定时器（每60秒保存一次）
    _autoSaveTimer = Timer.periodic(const Duration(seconds: 60), (_) {
      _autoSaveExamState();
    });
  }

  // 恢复考试状态
  void _restoreState(ExamState state) {
    setState(() {
      _answers = Map<String, dynamic>.from(state.answers);
      _remainingSeconds = state.remainingSeconds;
    });
    _startTimer();
  }

  // 开始新考试
  void _startNewExam() async {
    final userId = UserData.currentUser?.id ?? 'unknown';
    
    // 创建考试状态
    await ExamStateService.startExam(widget.exam.id, widget.exam.duration);
    
    setState(() {
      _remainingSeconds = widget.exam.duration * 60; // 转换为秒
    });
    _startTimer();
  }

  // 自动保存考试状态
  void _autoSaveExamState() {
    ExamStateService.autoSaveExamState(
      widget.exam.id,
      _answers,
      _remainingSeconds,
    ).then((success) {
      if (success) {
        debugPrint('考试状态自动保存成功');
      } else {
        debugPrint('考试状态自动保存失败');
      }
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    _timer?.cancel();
    _autoSaveTimer?.cancel();
    
    // 退出前保存一次状态
    if (!_isSubmitting) {
      _autoSaveExamState();
    }
    
    super.dispose();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_remainingSeconds > 0) {
          _remainingSeconds--;
        } else {
          _timer?.cancel();
          _submitExam(); // 时间结束自动提交
        }
      });
    });
  }

  String _formatTime(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;
    int secs = seconds % 60;
    
    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  void _submitExam() {
    if (_isSubmitting) return; // 防止重复提交
    
    // 重新计算未答题数量，同时考虑照片答案
    int answeredCount = 0;
    for (var question in widget.exam.questions) {
      if (_isQuestionAnswered(question.id)) {
        answeredCount++;
      }
    }
    
    int unansweredCount = widget.exam.questions.length - answeredCount;
    
    // 显示确认对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认提交'),
        content: Text(
          unansweredCount > 0
              ? '您还有 $unansweredCount 道题未作答，确定要提交吗？' 
              : '确定要提交考试吗？'
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
              _doSubmitExam(); // 执行提交
            },
            child: Text('确认提交'),
          ),
        ],
      ),
    );
  }
  
  // 实际执行提交的方法
  void _doSubmitExam() {
    setState(() {
      _isSubmitting = true;
    });
    
    // 创建考试结果
    ExamResult result = ExamResult.create(
      examId: widget.exam.id,
      userId: UserData.currentUser?.id ?? 'unknown',
      answers: _answers,
      avatarPath: widget.avatarPath,
    );
    
    // 如果有答题照片，添加到结果中
    for (var entry in _answerImages.entries) {
      for (var imagePath in entry.value) {
        result = result.addAnswerImage(entry.key, imagePath);
      }
    }
    
    // 计算考试用时（分钟）
    final examDurationInMinutes = widget.exam.duration;
    final usedTimeInMinutes = (examDurationInMinutes - (_remainingSeconds / 60)).ceil();
    
    // 保存结果并标记考试完成
    ExamStateService.completeExam(widget.exam.id, result).then((success) {
      if (success) {
        debugPrint('考试完成，结果已保存');
        
        // 导出考试结果到Excel
        ExamStateService.exportExamResultToExcel(
          result, 
          widget.exam,
          usedTimeInMinutes
        ).then((filePath) {
          if (filePath != null) {
            debugPrint('考试结果已导出至: $filePath');
            
            // 打包考试结果为ZIP文件
            ExamStateService.packageExamResultsToZip(
              result,
              widget.exam,
              usedTimeInMinutes,
              filePath
            ).then((zipFilePath) {
              if (zipFilePath != null) {
                debugPrint('考试结果和照片已打包成ZIP: $zipFilePath');
              } else {
                debugPrint('考试结果打包失败');
              }
            });
          } else {
            debugPrint('考试结果导出失败');
          }
        });
      } else {
        debugPrint('考试结果保存失败');
      }
    });
    
    // 导航到结果页面
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) => ResultScreen(exam: widget.exam, result: result),
        settings: RouteSettings(name: 'ResultScreen'),
      ),
    );
  }

  void _nextQuestion() {
    if (_currentIndex < widget.exam.questions.length - 1) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  void _previousQuestion() {
    if (_currentIndex > 0) {
      _pageController.previousPage(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  bool _isQuestionAnswered(String questionId) {
    // 检查是否有文字答案
    bool hasTextAnswer = _answers.containsKey(questionId) && _answers[questionId] != null;
    
    // 对于多选题，确保选择了至少一个选项
    if (hasTextAnswer && _answers[questionId] is List) {
      hasTextAnswer = (_answers[questionId] as List).isNotEmpty;
    }
    
    // 对于文本答案，确保不是空字符串
    if (hasTextAnswer && _answers[questionId] is String) {
      hasTextAnswer = (_answers[questionId] as String).trim().isNotEmpty;
    }
    
    // 检查是否有照片答案
    bool hasPhotoAnswer = _answerImages.containsKey(questionId) && 
                          _answerImages[questionId]!.isNotEmpty;
    
    // 如果有任一类型的答案，则认为问题已回答
    return hasTextAnswer || hasPhotoAnswer;
  }

  // 检查问题是否被标记
  bool _isQuestionMarked(String questionId) {
    return _markedQuestions.contains(questionId);
  }

  // 切换问题的标记状态
  void _toggleQuestionMark(String questionId) {
    setState(() {
      if (_markedQuestions.contains(questionId)) {
        _markedQuestions.remove(questionId);
      } else {
        _markedQuestions.add(questionId);
      }
    });
  }

  void _updateAnswer(String questionId, dynamic answer) {
    setState(() {
      _answers[questionId] = answer;
    });
  }

  @override
  Widget build(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    final double standardSpacing = 12.0; // 使用固定间距
    
    return WillPopScope(
      onWillPop: () async {
        // 拦截用户的返回操作，显示确认对话框
        final shouldPop = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('确认离开考试?'),
            content: const Text('离开将会保存当前答题状态，您可以稍后继续考试，但计时不会暂停。确定要离开吗?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.of(context).pop(true),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
                child: const Text('确认离开'),
              ),
            ],
          ),
        );
        return shouldPop ?? false;
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          title: Text(
            widget.exam.title,
            style: TextStyle(
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
              color: Colors.white,
              overflow: TextOverflow.ellipsis,
            ),
            maxLines: 1,
          ),
          backgroundColor: Colors.blue.shade800,
          foregroundColor: Colors.white,
          elevation: 0,
          toolbarHeight: 50.0, // 固定工具栏高度
          actions: [
            Center(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 4.0),
                margin: EdgeInsets.only(right: 12.0),
                decoration: BoxDecoration(
                  color: Colors.blue.shade700,
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Row(
                  children: [
                    Icon(Icons.timer, size: 14),
                    SizedBox(width: 4),
                    Text(
                      _formatTime(_remainingSeconds),
                      style: TextStyle(
                        fontSize: 14.0,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        endDrawer: _buildQuestionNavigationDrawer(),
        body: Column(
          children: [
            // 进度条
            LinearProgressIndicator(
              value: (_currentIndex + 1) / widget.exam.questions.length,
              backgroundColor: Colors.grey.shade200,
              valueColor: AlwaysStoppedAnimation<Color>(Colors.blue.shade600),
              minHeight: 3,
            ),
            
            // 问题计数器和已答题数
            Padding(
              padding: EdgeInsets.symmetric(
                horizontal: standardSpacing,
                vertical: 6.0,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                        decoration: BoxDecoration(
                          color: Colors.blue.shade100,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          '题目 ${_currentIndex + 1}/${widget.exam.questions.length}',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue.shade800,
                          ),
                        ),
                      ),
                      SizedBox(width: 8),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                        decoration: BoxDecoration(
                          color: _getAnsweredCount() == widget.exam.questions.length
                              ? Colors.green.shade100
                              : Colors.orange.shade100,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                          '已答: ${_getAnsweredCount()}/${widget.exam.questions.length}',
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: _getAnsweredCount() == widget.exam.questions.length
                                ? Colors.green.shade800
                                : Colors.orange.shade800,
                          ),
                        ),
                      ),
                    ],
                  ),
                  // 导航按钮
                  ElevatedButton.icon(
                    onPressed: () => _scaffoldKey.currentState?.openEndDrawer(),
                    icon: Icon(Icons.menu, size: 14),
                    label: Text(
                      '题目导航',
                      style: TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey.shade200,
                      foregroundColor: Colors.black87,
                      padding: EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      minimumSize: Size(10, 10),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 题目内容区域
            Expanded(
              child: PageView.builder(
                controller: _pageController,
                onPageChanged: (index) {
                  setState(() {
                    _currentIndex = index;
                  });
                },
                itemCount: widget.exam.questions.length,
                itemBuilder: (context, index) {
                  final question = widget.exam.questions[index];
                  return SingleChildScrollView(
                    padding: EdgeInsets.symmetric(
                      horizontal: standardSpacing,
                      vertical: 8.0,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildQuestionHeader(question, isTablet),
                        SizedBox(height: 12.0),
                        _buildQuestionContent(question, isTablet),
                        SizedBox(height: 16.0),
                      ],
                    ),
                  );
                },
              ),
            ),
            
            // 底部导航栏
            _buildBottomBar(isTablet),
          ],
        ),
      ),
    );
  }

  // 构建题目导航抽屉
  Widget _buildQuestionNavigationDrawer() {
    return Drawer(
      width: 280, // 减小宽度
      child: Column(
        children: [
          Container(
            color: Colors.blue.shade800,
            padding: EdgeInsets.symmetric(
              vertical: 12.0,
              horizontal: 16.0,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 24), // 为状态栏留出空间
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '题目导航',
                      style: TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                    IconButton(
                      icon: Icon(Icons.close, color: Colors.white, size: 20),
                      onPressed: () => Navigator.of(context).pop(),
                      constraints: BoxConstraints(
                        minWidth: 40,
                        minHeight: 40,
                      ),
                      padding: EdgeInsets.zero,
                    ),
                  ],
                ),
              ],
            ),
          ),
          // 状态指示说明
          Padding(
            padding: EdgeInsets.all(12.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatusIndicator(Colors.green.shade100, Colors.green, '已答题'),
                _buildStatusIndicator(Colors.grey.shade100, Colors.grey.shade500, '未答题'),
                _buildStatusIndicator(Colors.orange.shade100, Colors.orange, '已标记'),
                _buildStatusIndicator(Colors.deepOrange.shade100, Colors.deepOrange, '已答+标记'),
              ],
            ),
          ),
          Divider(height: 1),
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.symmetric(vertical: 8.0),
              itemCount: widget.exam.questions.length,
              itemBuilder: (context, index) {
                final question = widget.exam.questions[index];
                final String questionId = question.id;
                final bool isCurrentQuestion = index == _currentIndex;
                final bool isAnswered = _isQuestionAnswered(questionId);
                final bool isMarked = _isQuestionMarked(questionId);
                
                // 确定颜色和边框样式
                Color backgroundColor;
                Color borderColor;
                if (isCurrentQuestion) {
                  backgroundColor = Colors.blue.shade100;
                  borderColor = Colors.blue.shade800;
                } else if (isAnswered && isMarked) {
                  // 同时被标记和回答的问题
                  backgroundColor = Colors.green.shade50;
                  borderColor = Colors.orange.shade500;
                } else if (isAnswered) {
                  backgroundColor = Colors.green.shade50;
                  borderColor = Colors.green.shade300;
                } else if (isMarked) {
                  backgroundColor = Colors.orange.shade50;
                  borderColor = Colors.orange.shade300;
                } else {
                  backgroundColor = Colors.grey.shade50;
                  borderColor = Colors.grey.shade300;
                }
                  
                return InkWell(
                  onTap: () {
                    _pageController.animateToPage(
                      index,
                      duration: const Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                    Navigator.of(context).pop(); // 关闭抽屉
                  },
                  child: Container(
                    margin: EdgeInsets.symmetric(
                      horizontal: 12.0,
                      vertical: 3.0,
                    ),
                    padding: EdgeInsets.all(10.0),
                    decoration: BoxDecoration(
                      color: backgroundColor,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: borderColor),
                    ),
                    child: Row(
                      children: [
                        Container(
                          width: 24,
                          height: 24,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: isCurrentQuestion 
                                ? Colors.blue.shade800 
                                : isAnswered && isMarked
                                    ? Colors.deepOrange // 同时被标记和回答的问题使用深橙色
                                    : isAnswered 
                                        ? Colors.green 
                                        : isMarked
                                            ? Colors.orange
                                            : Colors.grey.shade400,
                          ),
                          child: Text(
                            '${index + 1}',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            _getQuestionTypeText(question.type),
                            style: TextStyle(
                              fontSize: 13,
                              fontWeight: isCurrentQuestion ? FontWeight.bold : FontWeight.normal,
                            ),
                          ),
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            if (isMarked)
                              Padding(
                                padding: EdgeInsets.only(right: isAnswered ? 4.0 : 0),
                                child: Icon(
                                  Icons.bookmark, 
                                  color: Colors.orange, 
                                  size: 16,
                                ),
                              ),
                            if (isAnswered)
                              Icon(
                                Icons.check_circle, 
                                color: Colors.green, 
                                size: 16,
                              ),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
          // 答题进度
          Container(
            padding: EdgeInsets.all(12.0),
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              border: Border(
                top: BorderSide(color: Colors.grey.shade300),
              ),
            ),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '已答: ${_getAnsweredCount()}/${widget.exam.questions.length}',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: _getAnsweredCount() == widget.exam.questions.length
                            ? Colors.green
                            : Colors.orange,
                      ),
                    ),
                    Text(
                      '已标记: ${_markedQuestions.length}',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: Colors.orange,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8),
                LinearProgressIndicator(
                  value: _getAnsweredCount() / widget.exam.questions.length,
                  backgroundColor: Colors.grey.shade300,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    _getAnsweredCount() == widget.exam.questions.length
                        ? Colors.green
                        : Colors.orange,
                  ),
                  minHeight: 6,
                ),
                SizedBox(height: 12),
                ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).pop(); // 先关闭抽屉
                    _submitExam(); // 然后调用提交方法
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red.shade700,
                    minimumSize: Size(double.infinity, 40),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text(
                    '提交考试',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建状态指示器
  Widget _buildStatusIndicator(Color backgroundColor, Color iconColor, String label) {
    return Row(
      children: [
        Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: backgroundColor,
            border: Border.all(color: iconColor),
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        SizedBox(width: 4),
        Text(
          label,
          style: TextStyle(fontSize: 12, color: Colors.grey.shade700),
        ),
      ],
    );
  }

  Widget _buildQuestionHeader(Question question, bool isTablet) {
    String typeText = _getQuestionTypeText(question.type);
    final bool isMarked = _isQuestionMarked(question.id);
    
    return Container(
      padding: EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.blue.shade100),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade100,
                      borderRadius: BorderRadius.circular(12.0),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          _getIconForQuestionType(question.type),
                          color: Colors.blue.shade700,
                          size: 14.0,
                        ),
                        SizedBox(width: 4.0),
                        Text(
                          typeText,
                          style: TextStyle(
                            fontSize: 12.0,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue.shade800,
                          ),
                        ),
                      ],
                    ),
              ),
              // 标记按钮
              InkWell(
                onTap: () => _toggleQuestionMark(question.id),
                borderRadius: BorderRadius.circular(20),
                child: Container(
                  padding: EdgeInsets.all(6),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: isMarked ? Colors.orange.shade100 : Colors.transparent,
                  ),
                  child: Icon(
                    isMarked ? Icons.bookmark : Icons.bookmark_border,
                    color: isMarked ? Colors.orange : Colors.grey.shade600,
                    size: 20,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 12.0),
          Text(
            question.text,
            style: TextStyle(
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
          ),
        ],
      ),
    );
  }

  // 修改底部导航栏，使其更紧凑
  Widget _buildBottomBar(bool isTablet) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 12.0,
        vertical: 6.0,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 3,
            offset: Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 上一题按钮
          OutlinedButton.icon(
            onPressed: _currentIndex > 0 ? _previousQuestion : null,
            icon: Icon(Icons.arrow_back_ios, size: 12),
            label: Text('上一题', style: TextStyle(fontSize: 12)),
            style: OutlinedButton.styleFrom(
              side: BorderSide(
                color: _currentIndex > 0 ? Colors.blue : Colors.grey.shade300,
                width: 1.0,
              ),
              foregroundColor: _currentIndex > 0 ? Colors.blue : Colors.grey,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
              minimumSize: Size(80, 32),
              padding: EdgeInsets.symmetric(horizontal: 6, vertical: 0),
            ),
          ),
          
          // 提交按钮
          ElevatedButton(
            onPressed: _submitExam,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red.shade700,
              disabledBackgroundColor: Colors.red.shade200,
              minimumSize: Size(80, 32),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 0),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
            ),
            child: Text(
              '提交考试',
              style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          
          // 下一题按钮
          OutlinedButton.icon(
            onPressed: _currentIndex < widget.exam.questions.length - 1 ? _nextQuestion : null,
            icon: Icon(Icons.arrow_forward_ios, size: 12),
            label: Text('下一题', style: TextStyle(fontSize: 12)),
            style: OutlinedButton.styleFrom(
              side: BorderSide(
                color: _currentIndex < widget.exam.questions.length - 1 ? Colors.blue : Colors.grey.shade300,
                width: 1.0,
              ),
              foregroundColor: _currentIndex < widget.exam.questions.length - 1 ? Colors.blue : Colors.grey,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(6),
              ),
              minimumSize: Size(80, 32),
              padding: EdgeInsets.symmetric(horizontal: 6, vertical: 0),
            ),
          ),
        ],
      ),
    );
  }

  String _getQuestionTypeText(QuestionType type) {
    switch (type) {
      case QuestionType.singleChoice:
        return '单选题';
      case QuestionType.multipleChoice:
        return '多选题';
      case QuestionType.fillBlank:
        return '填空题';
      case QuestionType.trueOrFalse:
        return '判断题';
      case QuestionType.shortAnswer:
        return '简答题';
    }
  }

  IconData _getIconForQuestionType(QuestionType type) {
    switch (type) {
      case QuestionType.singleChoice:
        return Icons.radio_button_checked;
      case QuestionType.multipleChoice:
        return Icons.check_box;
      case QuestionType.fillBlank:
        return Icons.short_text;
      case QuestionType.trueOrFalse:
        return Icons.rule;
      case QuestionType.shortAnswer:
        return Icons.notes;
    }
  }

  Widget _buildQuestionContent(Question question, bool isTablet) {
    switch (question.type) {
      case QuestionType.singleChoice:
        return _buildSingleChoiceQuestion(question as SingleChoiceQuestion, isTablet);
      case QuestionType.multipleChoice:
        return _buildMultipleChoiceQuestion(question as MultipleChoiceQuestion, isTablet);
      case QuestionType.fillBlank:
        return _buildFillBlankQuestion(question as FillBlankQuestion, isTablet);
      case QuestionType.trueOrFalse:
        return _buildTrueOrFalseQuestion(question as TrueOrFalseQuestion, isTablet);
      case QuestionType.shortAnswer:
        return _buildShortAnswerQuestion(question as ShortAnswerQuestion, isTablet);
    }
  }

  Widget _buildSingleChoiceQuestion(SingleChoiceQuestion question, bool isTablet) {
    return Card(
      elevation: 1,
      margin: EdgeInsets.only(top: 12.0),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8.0),
        side: BorderSide(color: Colors.grey.shade200),
      ),
      child: Padding(
        padding: EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 选项
            ...question.choices.map((choice) {
              final isSelected = _answers[question.id] == choice.id;
              return Container(
                margin: EdgeInsets.symmetric(vertical: 3.0),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.blue.shade50 : Colors.transparent,
                  borderRadius: BorderRadius.circular(6.0),
                  border: Border.all(
                    color: isSelected ? Colors.blue.shade400 : Colors.grey.shade300,
                  ),
                ),
                child: RadioListTile<String>(
                  title: Text(
                    "${choice.id}. ${choice.text}",
                    style: TextStyle(
                      fontSize: 14.0,
                    ),
                  ),
                  value: choice.id,
                  groupValue: _answers[question.id] as String?,
                  onChanged: (value) {
                    _updateAnswer(question.id, value);
                  },
                  activeColor: Colors.blue.shade800,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 10.0, 
                    vertical: 6.0,
                  ),
                  dense: true,
                  secondary: isSelected 
                      ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                      : null,
                ),
              );
            }).toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildMultipleChoiceQuestion(MultipleChoiceQuestion question, bool isTablet) {
    // Ensure _answers[question.id] is a List<String>
    if (_answers[question.id] == null) {
      _answers[question.id] = <String>[];
    }

    final selectedOptions = _answers[question.id] as List<dynamic>? ?? [];

    return Card(
      elevation: 1,
      margin: EdgeInsets.only(top: 12.0),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8.0),
        side: BorderSide(color: Colors.grey.shade200),
      ),
      child: Padding(
        padding: EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 选项
            ...question.choices.map((choice) {
              final isSelected = selectedOptions.contains(choice.id);
              return Container(
                margin: EdgeInsets.symmetric(vertical: 3.0),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.blue.shade50 : Colors.transparent,
                  borderRadius: BorderRadius.circular(6.0),
                  border: Border.all(
                    color: isSelected ? Colors.blue.shade400 : Colors.grey.shade300,
                  ),
                ),
                child: CheckboxListTile(
                  title: Text(
                    "${choice.id}. ${choice.text}",
                    style: TextStyle(
                      fontSize: 14.0,
                    ),
                  ),
                  value: isSelected,
                  onChanged: (checked) {
                    setState(() {
                      final List<String> updatedList = List<String>.from(selectedOptions.map((e) => e.toString()));
                      if (checked == true) {
                        if (!updatedList.contains(choice.id)) {
                          updatedList.add(choice.id);
                        }
                      } else {
                        updatedList.remove(choice.id);
                      }
                      _updateAnswer(question.id, updatedList);
                    });
                  },
                  activeColor: Colors.blue.shade800,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 10.0, 
                    vertical: 6.0,
                  ),
                  dense: true,
                  checkColor: Colors.white,
                  secondary: isSelected
                      ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                      : null,
                ),
              );
            }).toList(),
          ],
        ),
      ),
    );
  }

  Widget _buildFillBlankQuestion(FillBlankQuestion question, bool isTablet) {
    return Container(
      margin: EdgeInsets.only(top: 12.0),
      padding: EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.grey.shade300),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade100,
            blurRadius: 3,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '请填写答案：',
            style: TextStyle(
              fontSize: 14.0,
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade700,
            ),
          ),
          SizedBox(height: 10.0),
          TextField(
            onChanged: (value) {
              _updateAnswer(question.id, value);
            },
            decoration: InputDecoration(
              hintText: '请输入答案',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(6.0),
                borderSide: BorderSide(color: Colors.blue.shade200),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(6.0),
                borderSide: BorderSide(color: Colors.blue.shade700, width: 2),
              ),
              contentPadding: EdgeInsets.symmetric(
                horizontal: 12.0,
                vertical: 10.0,
              ),
              filled: true,
              fillColor: Colors.grey.shade50,
              hintStyle: TextStyle(fontSize: 14.0),
            ),
            controller: TextEditingController(text: _answers[question.id] as String? ?? ''),
            style: TextStyle(fontSize: 14.0),
          ),
        ],
      ),
    );
  }

  Widget _buildTrueOrFalseQuestion(TrueOrFalseQuestion question, bool isTablet) {
    return Card(
      elevation: 1,
      margin: EdgeInsets.only(top: 12.0),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8.0),
        side: BorderSide(color: Colors.grey.shade200),
      ),
      child: Padding(
        padding: EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 3.0),
              decoration: BoxDecoration(
                color: _answers[question.id] == true ? Colors.blue.shade50 : Colors.transparent,
                borderRadius: BorderRadius.circular(6.0),
                border: Border.all(
                  color: _answers[question.id] == true ? Colors.blue.shade400 : Colors.grey.shade300,
                ),
              ),
              child: RadioListTile<bool>(
                title: Text(
                  '正确',
                  style: TextStyle(
                    fontSize: 14.0,
                  ),
                ),
                value: true,
                groupValue: _answers[question.id] as bool?,
                onChanged: (value) {
                  _updateAnswer(question.id, value);
                },
                activeColor: Colors.blue.shade800,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 10.0, 
                  vertical: 6.0,
                ),
                dense: true,
                secondary: _answers[question.id] == true 
                    ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                    : null,
              ),
            ),
            SizedBox(height: 6.0),
            Container(
              margin: EdgeInsets.symmetric(vertical: 3.0),
              decoration: BoxDecoration(
                color: _answers[question.id] == false ? Colors.blue.shade50 : Colors.transparent,
                borderRadius: BorderRadius.circular(6.0),
                border: Border.all(
                  color: _answers[question.id] == false ? Colors.blue.shade400 : Colors.grey.shade300,
                ),
              ),
              child: RadioListTile<bool>(
                title: Text(
                  '错误',
                  style: TextStyle(
                    fontSize: 14.0,
                  ),
                ),
                value: false,
                groupValue: _answers[question.id] as bool?,
                onChanged: (value) {
                  _updateAnswer(question.id, value);
                },
                activeColor: Colors.blue.shade800,
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 10.0, 
                  vertical: 6.0,
                ),
                dense: true,
                secondary: _answers[question.id] == false 
                    ? Icon(Icons.check_circle, color: Colors.green, size: 20.0)
                    : null,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildShortAnswerQuestion(ShortAnswerQuestion question, bool isTablet) {
    // 获取当前问题的答题照片
    final List<String> answerImages = _getAnswerImages(question.id);
    
    return Container(
      margin: EdgeInsets.only(top: 12.0),
      padding: EdgeInsets.all(12.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.0),
        border: Border.all(color: Colors.grey.shade300),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.shade100,
            blurRadius: 3,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '请输入答案或上传照片：',
            style: TextStyle(
              fontSize: 14.0,
              fontWeight: FontWeight.bold,
              color: Colors.grey.shade700,
            ),
          ),
          SizedBox(height: 10.0),
          TextField(
            onChanged: (value) {
              _updateAnswer(question.id, value);
            },
            maxLines: 4,
            minLines: 3,
            decoration: InputDecoration(
              hintText: '可以在此输入文字答案，或直接通过下方按钮上传照片',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(6.0),
                borderSide: BorderSide(color: Colors.blue.shade200),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(6.0),
                borderSide: BorderSide(color: Colors.blue.shade700, width: 2),
              ),
              contentPadding: EdgeInsets.symmetric(
                horizontal: 12.0,
                vertical: 10.0,
              ),
              filled: true,
              fillColor: Colors.grey.shade50,
              hintStyle: TextStyle(fontSize: 14.0),
            ),
            controller: TextEditingController(text: _answers[question.id] as String? ?? ''),
            style: TextStyle(fontSize: 14.0),
          ),
          SizedBox(height: 16.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '添加答题照片：',
                style: TextStyle(
                  fontSize: 14.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.grey.shade700,
                ),
              ),
              Row(
                children: [
                  // 拍照按钮
                  ElevatedButton.icon(
                    onPressed: () => _takePhoto(question.id),
                    icon: Icon(Icons.camera_alt, size: 16.0),
                    label: Text('拍照'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue.shade600,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
                      textStyle: TextStyle(fontSize: 12.0),
                    ),
                  ),
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0),
                      textStyle: TextStyle(fontSize: 12.0),
                    ),
                  ),
                ],
              ),
            ],
          ),
          // 显示已添加的照片
          if (answerImages.isNotEmpty) ...[
            SizedBox(height: 12.0),
            Text(
              '已添加的照片：',
              style: TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade700,
              ),
            ),
            SizedBox(height: 8.0),
            Container(
              height: 100.0,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: answerImages.length,
                itemBuilder: (context, index) {
                  return Container(
                    margin: EdgeInsets.only(right: 8.0),
                    width: 100.0,
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey.shade300),
                      borderRadius: BorderRadius.circular(4.0),
                    ),
                    child: Stack(
                      children: [
                        // 显示图片
                        Center(
                          child: Image.file(
                            File(answerImages[index]),
                            fit: BoxFit.cover,
                            width: 100.0,
                            height: 100.0,
                          ),
                        ),
                        // 删除按钮
                        Positioned(
                          top: 0,
                          right: 0,
                          child: InkWell(
                            onTap: () => _removeAnswerImage(question.id, answerImages[index]),
                            child: Container(
                              padding: EdgeInsets.all(4.0),
                              decoration: BoxDecoration(
                                color: Colors.red.withOpacity(0.7),
                                shape: BoxShape.circle,
                              ),
                              child: Icon(
                                Icons.close,
                                size: 14.0,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 获取问题的答题照片
  List<String> _getAnswerImages(String questionId) {
    return _answerImages[questionId] ?? [];
  }
  
  // 拍照并添加到答题照片
  Future<void> _takePhoto(String questionId) async {
    // 获取题目类型，确保只有简答题能添加照片
    final Question? question = _findQuestionById(questionId);
    if (question == null || question.type != QuestionType.shortAnswer) {
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('只有简答题支持照片上传'),
          backgroundColor: Colors.red.shade600,
        ),
      );
      return;
    }
    
    final File? photo = await ImageService.takePhoto();
    if (photo != null) {
      _addAnswerImage(questionId, photo.path);
    }
  }
  
  // 从相册选择图片并添加到答题照片
  Future<void> _pickImage(String questionId) async {
    // 获取题目类型，确保只有简答题能添加照片
    final Question? question = _findQuestionById(questionId);
    if (question == null || question.type != QuestionType.shortAnswer) {
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('只有简答题支持照片上传'),
          backgroundColor: Colors.red.shade600,
        ),
      );
      return;
    }
    
    final File? image = await ImageService.pickImageFromGallery();
    if (image != null) {
      _addAnswerImage(questionId, image.path);
    }
  }
  
  // 添加答题照片
  void _addAnswerImage(String questionId, String imagePath) {
    setState(() {
      if (_answerImages.containsKey(questionId)) {
        _answerImages[questionId]!.add(imagePath);
      } else {
        _answerImages[questionId] = [imagePath];
      }
    });
    
    // 自动保存考试状态
    _saveExamState();
  }
  
  // 删除答题照片
  void _removeAnswerImage(String questionId, String imagePath) {
    setState(() {
      if (_answerImages.containsKey(questionId)) {
        _answerImages[questionId]!.remove(imagePath);
        
        // 如果列表为空，删除该键
        if (_answerImages[questionId]!.isEmpty) {
          _answerImages.remove(questionId);
        }
      }
    });
    
    // 删除文件
    ImageService.deleteImage(imagePath);
    
    // 自动保存考试状态
    _saveExamState();
  }
  
  // 保存考试状态
  Future<void> _saveExamState() async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) return;
    
    // 构建包含答题照片的完整答案
    final Map<String, dynamic> completeAnswers = Map<String, dynamic>.from(_answers);
    
    // 添加答题照片信息
    if (_answerImages.isNotEmpty) {
      completeAnswers['_answerImages'] = _answerImages;
    }
    
    await ExamStateService.autoSaveExamState(
      widget.exam.id,
      completeAnswers,
      _remainingSeconds,
    );
  }

  // 计算已回答题目的数量（包含文字答案和照片答案）
  int _getAnsweredCount() {
    // 创建一个集合存储已回答的题目ID
    Set<String> answeredQuestionIds = {};
    
    // 添加有文字答案的题目
    for (var questionId in _answers.keys) {
      if (_answers[questionId] != null) {
        // 对于多选题，确保选择了至少一个选项
        if (_answers[questionId] is List && (_answers[questionId] as List).isEmpty) {
          continue;
        }
        
        // 对于文本答案，确保不是空字符串
        if (_answers[questionId] is String && (_answers[questionId] as String).trim().isEmpty) {
          continue;
        }
        
        answeredQuestionIds.add(questionId);
      }
    }
    
    // 添加有照片答案的题目
    for (var questionId in _answerImages.keys) {
      if (_answerImages[questionId] != null && _answerImages[questionId]!.isNotEmpty) {
        answeredQuestionIds.add(questionId);
      }
    }
    
    return answeredQuestionIds.length;
  }

  // 根据ID查找题目
  Question? _findQuestionById(String questionId) {
    for (var question in widget.exam.questions) {
      if (question.id == questionId) {
        return question;
      }
    }
    return null;
  }
} 